package com.zero.manage.web.components.base;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.core.types.Predicate;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 所有查询类的基类
 *
 * @author zero
 */
@NoArgsConstructor
@AllArgsConstructor
public abstract class BaseQuery {
    @ApiModelProperty("第几页")
    @Setter
    @Getter
    private int page = 1;

    @ApiModelProperty("显示多少条")
    @Setter
    @Getter
    private int pageSize = 10;

    @ApiModelProperty(
            value = "排序",
            example = "{\"createTime\":\"desc\",\"zero\":\"asc\"}"
    )
    @Setter
    protected LinkedHashMap<String, String> sortMap;

    /**
     * 这儿要考虑默认的（后端固定排序）和前端动态排序
     * 如果前端传了排序规则，那么后端的排序就不使用
     *
     * @return
     */
    private LinkedHashMap<String, String> getSortMap() {
        return CollectionUtils.isEmpty(sortMap) ? this.initSort() : sortMap;
    }

    /**
     * 定义一个初始化排序方法
     *
     * @return
     */
    protected LinkedHashMap<String, String> initSort() {
        return null;
    }

    /**
     * 条件获取
     */
    public Predicate predicate() {
        return new BooleanBuilder();
    }

    /**
     * 分页获取
     *
     * @return
     */
    @JsonIgnore
    public Pageable getPageable() {
        return PageRequest.of(page - 1, pageSize, getSort());
    }

    /**
     * 排序获取
     *
     * @return
     */
    @JsonIgnore
    public Sort getSort() {
        //设置后台默认排序
        Sort sort = Sort.unsorted();
        List<Sort.Order> orderList = new ArrayList<>();
        LinkedHashMap<String, String> sortMap = getSortMap();
        if (!CollectionUtils.isEmpty(sortMap)) {
            for (Map.Entry<String, String> entry : sortMap.entrySet()) {
                String mapKey = entry.getKey();
                String mapValue = entry.getValue();
                //默认正序
                Sort.Direction direction = Sort.Direction.ASC;
                if (Sort.Direction.DESC.toString().equalsIgnoreCase(mapValue)) {
                    direction = Sort.Direction.DESC;
                }
                orderList.add(new Sort.Order(direction, mapKey));
            }
        }
        if (!CollectionUtils.isEmpty(orderList)) {
            sort = Sort.by(orderList);
        }
        return sort;
    }
}

